export const getUid = (() => {
  let i = 1;
  return () => ++i;
})();

export const getZindex = (() => {
  let i = 1000;
  return () => ++i;
})();

export function ready(fn) {
  document.addEventListener('DOMContentLoaded', fn);
}

export function each(arr, fn) {
  for (let i = 0; i < arr.length; i++) {
    fn(arr[i], i);
  }
}

export function addClass(el, classNames) {
  if (Array.isArray(classNames)) {
    el.classList.add.apply(el.classList, classNames);
  } else {
    el.classList.add(classNames);
  }
}

export function removeClass(el, classNames) {
  if (Array.isArray(classNames)) {
    el.classList.remove.apply(el.classList, classNames);
  } else {
    el.classList.remove(classNames);
  }
}

export function qs(selector) {
  return document.querySelector(selector);
}

export function qsa(selector) {
  const els = document.querySelectorAll(selector)
  return els ? els : [];
}

/**
 * @param {Element|Window|Document} el
 * @param {string} eventName
 * @param {Function} handler
 * @param {boolean} [useCapture=false] 是否在捕获阶段触发事件，默认为false
 */
export function addEvent(el, eventName, handler, useCapture = false) {
  el.addEventListener(eventName, handler, useCapture);
}

/**
 * @param {Element|Window|Document} el
 * @param {string} eventName
 * @param {Function} handler
 * @param {boolean} [useCapture=false] 是否在捕获阶段触发事件，默认为false
 */
export function removeEvent(el, eventName, handler, useCapture = false) {
  el.removeEventListener(eventName, handler, useCapture);
}

export function getType(args) {
  return Object.prototype.toString.call(args)
    .replace(/\[|\]/g, '')
    .split(/\s+/)[1]
    .toLocaleLowerCase();
}

export function debounce() {
  var timeout;
  return function () {
    var ctx = this;
    var args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      fn.apply(ctx, args);
    }, wait);
  }
}

export function throttle() {
  var cooldown = false;
  return function () {
    var ctx = this;
    var args = arguments;
    if (!cooldown) {
      fn.apply(ctx, args);
      cooldown = true;
      setTimeout(function () {
        cooldown = false;
      }, wait);
    }
  }
}

export function setAttr(el, name, value) {
  el.setAttribute(name, value);
}

export function getAttr(el, name) {
  el.getAttribute(name);
}

export function removeAttr(el, name) {
  el.removeAttribute(name);
}

export function setCss(el, ...arr) {
  for (let index = 0; index < arr.length; index++) {
    const args = arr[index];
    for (const key in args) {
      if (Object.prototype.hasOwnProperty.call(args, key)) {
        const value = args[key];
        el.style.setProperty(key, value);
      }
    }
  }
}
